﻿/****************************************************************************************
*	Mouzetrap - client/server framework	
*
*	$HeadURL: http://mouzetrap.googlecode.com/svn/trunk/Mouzetrap/DataStructures/BoundedLockfreeQueue.cs $
*	$Id: BoundedLockfreeQueue.cs 11 2009-06-11 09:10:25Z tobz@fallenrealms.net $
*
*	Original copyright Julian M Bucknall (www.boyet.com) 
* 
*	Copyright (c) 2008 Toby Lawrence
* 
*	Permission is hereby granted, free of charge, to any person obtaining a copy
*	of this software and associated documentation files (the "Software"), to deal
*	in the Software without restriction, including without limitation the rights
*	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*	copies of the Software, and to permit persons to whom the Software is
*	furnished to do so, subject to the following conditions:
* 
*	The above copyright notice and this permission notice shall be included in
*	all copies or substantial portions of the Software.
* 
*	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*	THE SOFTWARE.
* 
****************************************************************************************/

using System;
using System.Threading;
using Mouzetrap.Localization;

namespace Mouzetrap.DataStructures
{
	/// <summary>
	/// Represents a variable size first-in-first-out (FIFO) collection of instances of the same arbitrary type 
	/// which has a fixed capacity.
	/// </summary>
	/// <typeparam name="T">the type of the elements in the queue</typeparam>
	/// <remarks>This collection is thread-safe.  Synchronization is provided via interlocked operations.</remarks>
	public class BoundedLockfreeQueue<T>
	{
		private readonly Semaphore _freeSlots;
		private readonly Semaphore _occupiedSlots;
		private ItemNode<T> _head;
		private ItemNode<T> _tail;

		/// <summary>
		/// Creates a new lock-free queue with no upper-bound on item capacity.
		/// </summary>
		public BoundedLockfreeQueue()
		{
			_tail = _head = new ItemNode<T>();
			_occupiedSlots = new Semaphore(0, int.MaxValue);
		}

		/// <summary>
		/// Creates a new lock-free queue with the given upper-bound on capacity.
		/// </summary>
		public BoundedLockfreeQueue(int itemCapacity)
		{
			if(itemCapacity < 1)
				throw new ArgumentOutOfRangeException(Mouzetrap_Messages.CapacityZero);

			_tail = _head = new ItemNode<T>();
			_freeSlots = new Semaphore(itemCapacity, itemCapacity);
			_occupiedSlots = new Semaphore(0, itemCapacity);
		}

		/// <summary>
		/// Inserts an item at the front of the queue.
		/// </summary>
		/// <param name="item">the item to insert in the queue</param>
		public void Enqueue(T item)
		{
			ItemNode<T> oldTail = null;
			ItemNode<T> oldTailNext;

			var newNode = new ItemNode<T>(item);

			// wait for free slots to add the item
			if(_freeSlots != null)
			{
				_freeSlots.WaitOne();
			}

			bool newNodeWasAdded = false;
			while(!newNodeWasAdded)
			{
				oldTail = _tail;
				oldTailNext = oldTail.Next;

				if(_tail == oldTail)
				{
					if(oldTailNext == null)
					{
						newNodeWasAdded = SyncUtilities.CompareAndSwap(ref _tail.Next, null, newNode);
					}
					else
					{
						SyncUtilities.CompareAndSwap(ref _tail, oldTail, oldTailNext);
					}
				}
			}

			SyncUtilities.CompareAndSwap(ref _tail, oldTail, newNode);

			// notify a waiting reader we've inserted an object.
			_occupiedSlots.Release();
		}

		/// <summary>
		/// Removes an item from the end of the queue.
		/// </summary>
		/// <returns>the first item from the end of the queue</returns>
		public T Dequeue()
		{
			T item = default(T);
			ItemNode<T> oldHead = null;

			bool haveAdvancedHead = false;
			while(!haveAdvancedHead)
			{
				oldHead = _head;
				ItemNode<T> oldTail = _tail;
				ItemNode<T> oldHeadNext = oldHead.Next;

				if(oldHead == _head)
				{
					if(oldHead == oldTail)
					{
						if(oldHeadNext == null)
						{
							// block and then reloop to try again.
							_occupiedSlots.WaitOne();

							continue;
						}

						SyncUtilities.CompareAndSwap(ref _tail, oldTail, oldHeadNext);
					}
					else
					{
						item = oldHeadNext.Item;

						haveAdvancedHead =
							SyncUtilities.CompareAndSwap(ref _head, oldHead, oldHeadNext);
					}
				}
			}

			// release back to the free slots so insertions can proceed
			if(_freeSlots != null)
			{
				_freeSlots.Release();
			}

			return item;
		}
	}
}